layui.define(function (exports) {
  "use strict";

  var router = {
    index: "/",
    lash: null,
    routers: {},
    init: function (options) {
      router.index = router.routerInfo(options.index).path.join("/");
      if (options.pop && typeof options.pop === "function") {
        router.pop = options.pop;
      }
      if (options.notFound && typeof options.notFound === "function") {
        router.notFound = options.notFound;
      }
      router.onhashchange();
      return this;
    },
    reg: function (hash, handler) {
      if (hash) {
        if (!handler) {
          handler = function () {};
        }
        if (hash instanceof Array) {
          for (var i in hash) {
            this.reg.apply(this, [hash[i], handler]);
          }
        } else if (typeof hash === "string") {
          hash = router.routerInfo(hash).path.join("/");
          if (typeof handler === "function") {
            router.routers[hash] = handler;
          } else if (typeof handler === "string" && router[handler]) {
            router.routers[hash] = router.routers[handler];
          }
        }
      }
      return this;
    },
    routerInfo: function (url) {
      url || (url = location.hash);
      var hash = url.replace(/^#+/g, "").replace(/\/+/g, "/");
      if (hash.indexOf("/") !== 0) {
        hash = "/" + hash;
      }
      return layui.router("#" + hash);
    },
    refresh: function (url) {
      router.onhashchange(url, true);
    },
    go: function (hash) {
      location.hash = "#" + router.routerInfo(hash).href;
    },
    onhashchange: function (url, refresh) {
      var routerInfo = router.routerInfo(url);
      router.lash = routerInfo.href;
      var hash = routerInfo.path.join("/");
      if (!hash || hash === "/") {
        hash = router.index;
        routerInfo = router.routerInfo(router.index);
      }
      router.pop && router.pop.call(this, routerInfo);
      if (router.routers[hash]) {
        routerInfo.refresh = refresh;
        router.routers[hash].call(this, routerInfo);
      } else if (router.notFound) {
        router.notFound.call(this, routerInfo);
      }
    },
  };

  window.onhashchange = function () {
    router.onhashchange();
  };
  exports("plusRouter", router);
});
